﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Nuanyang.Asp.Net.Core.Extension.DataBase;
using Serilog;
using Serilog.Core;
using Serilog.Sinks.Elasticsearch;

namespace Nuanyang.Asp.Net.Core.Extension
{
    public static class ServiceExtension
    {
        private static Logger _log;

        /// <summary>
        /// 添加权限全局上下文
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddFunctionContext(this IServiceCollection services, Action<DbContextOptionsBuilder> optionsAction = null, ServiceLifetime contextLifetime = ServiceLifetime.Singleton, ServiceLifetime optionsLifetime = ServiceLifetime.Singleton)
        {
            services.AddDbContext<FunctionContext>(optionsAction, contextLifetime, optionsLifetime);
            return services;
        }

        /// <summary>
        /// 添加全局日志收集记录到本地
        /// </summary>
        /// <param name="services"></param>
        /// <param name="logName">日志文件名及其路径（只写名字默认为相对当前路径）</param>
        /// <returns></returns>
        public static IServiceCollection AddGlobalLogger2File(this IServiceCollection services, string logName = "applicationLog.log")
        {
            _log = new LoggerConfiguration().WriteTo.File(logName, rollingInterval: RollingInterval.Day).CreateLogger();
            services.AddSingleton(getLog);        
            return services;
        }


        /// <summary>
        /// 添加全局日志收集记录到本地
        /// </summary>
        /// <param name="services"></param>
        /// <param name="logName">日志文件名及其路径（只写名字默认为相对当前路径）</param>
        /// <returns></returns>
        public static IServiceCollection AddGlobalLogger2Elsticsearch(this IServiceCollection services, ElasticsearchSinkOptions elasticsearchSinkOptions = null)
        {
            if (elasticsearchSinkOptions == null)
                elasticsearchSinkOptions = new ElasticsearchSinkOptions(new Uri("http://localhost:9200") ) { AutoRegisterTemplate = true };
            _log = new LoggerConfiguration().WriteTo.Elasticsearch(elasticsearchSinkOptions).CreateLogger();
            services.AddSingleton(getLog);
            return services;
        }

        private static ILogger getLog(IServiceProvider arg)
        {
            return _log;
        }
    }
}
